<template>
  <div>
    <hs-breadcrumb :breadcrumb="breadcrumb"></hs-breadcrumb>
    <Card :bordered="false" :style="{ marginBottom: '10px' }">
      <div class="hs-screen-row">
        <Input
          v-model="params.username"
          placeholder="手机号"
          clearable
          style="width: 200px"
        />
      </div>
      <div class="hs-screen-row">
        <Input
          v-model="params.voucherCode"
          placeholder="核销码"
          clearable
          style="width: 200px"
        />
      </div>
      <div class="hs-screen-row">
        <Input
          v-model="params.poiName"
          placeholder="核销门店"
          clearable
          style="width: 200px"
        />
      </div>
      <div class="hs-screen-row">
        <Select
          v-model="params.orderState"
          placeholder="订单状态"
          clearable
          style="width:200px"
        >
          <Option value="">全部</Option>
          <Option v-for="item in ORDER_STATE_LIST" :value="item.value">
            {{ item.label }}
          </Option>
        </Select>
      </div>
      <div class="hs-screen-row">
        <DatePicker
          @on-change="changeDate"
          v-model="dateInit"
          type="daterange"
          :editable="false"
          separator=" ~ "
          split-panels
          transfer
          placeholder="核销时间"
          style="width: 200px"
        ></DatePicker>
      </div>
      <div class="hs-screen-row">
        <Button type="primary" @click="findOrderMallList">查询</Button>
      </div>
      <div class="hs-screen-row">
        <Button @click="resetScreen">重置</Button>
      </div>
    </Card>

    <Card :bordered="false" :style="{ marginBottom: '10px' }">
      <!--标题-->
      <div slot="title">
        <div class="hs-screen-box">
          <div>手动录单</div>
          <div>
            <ButtonGroup>
              <Button @click="findOrderMallList">
                <Icon type="md-refresh" size="15" />
              </Button>
            </ButtonGroup>
          </div>
        </div>
      </div>
      <div style="margin-bottom: 10px">
        <Button type="dashed" @click="addHandle">新增</Button>
        <Button
          style="margin-left: 10px"
          type="dashed"
          @click="isShowImport = true"
        >
          批量新增
        </Button>
      </div>
      <!--表格数据-->
      <Table
        :columns="columns"
        :data="data"
        size="small"
        :stripe="true"
        :loading="isTableLoading"
        @on-select="selectTable"
        @on-select-cancel="selectCancelTable"
        @on-select-all="selectAllTable"
        @on-select-all-cancel="selectAllCancelTable"
      >
        <!-- 订单状态：1.待付款；2.待发货；3.待工厂收件  4.清洗中；11.待打包； 12.待寄回；13、待到货； 14.待确收；30已完成；99 失效 -->
        <template slot-scope="{ row, index }" slot="orderState">
          <span
            v-for="item in ORDER_STATE_LIST"
            v-if="row.orderState == item.value"
          >
            {{ item.label }}
          </span>
        </template>

        <template slot-scope="{ row, index }" slot="totalFreight">
          <span>{{ row.totalFreight ? row.totalFreight : 0 }}</span>
        </template>

        <template slot-scope="{ row, index }" slot="balanceDeduction">
          <span>{{ row.balanceDeduction ? row.balanceDeduction : '-' }}</span>
        </template>

        <template slot-scope="{ row }" slot="action">
          <Button
            type="success"
            size="small"
            style="margin-right: 5px"
            @click="showOrderOpe(row)"
          >
            查看
          </Button>
        </template>
      </Table>
      <!--分页-->
      <div class="hs-page">
        <Page
          :total="total"
          show-sizer
          show-total
          transfer
          @on-change="changePage"
          @on-page-size-change="changePageSize"
        />
      </div>
    </Card>

    <!--显示模态框-->
    <order-ope ref="orderOpe"></order-ope>
    <!-- 新增 -->
    <add-order-ope
      ref="addOrderOpe"
      @confirm="findOrderMallList"
    ></add-order-ope>
  </div>
</template>

<script>
  import hsBreadcrumb from '@/components/hs-breadcrumb';
  import orderOpe from './components/order-ope';
  import addOrderOpe from './components/add-order-ope';
  import { ORDER_STATE_LIST } from '@/constant/order.js';

  export default {
    name: 'admin',
    data() {
      return {
        ORDER_STATE_LIST,
        total: 0,
        importSuccess: 0,
        importFailed: 0,
        dateInit: '',
        isTableLoading: false,
        isShowImport: false,
        // 选中数据
        selectData: [],
        action: this.$apiURL + '/orderMall/importOrder',
        headers: {
          token: JSON.parse(sessionStorage.getItem('J-TOKEN')).token
        },
        // 参数
        params: {
          page: 1,
          rows: 10,
          code: '',
          mallOrderCode: '',
          orderState: '',
          nickName: '',
          mobile: '',
          maskPhone: '',
          consigneeName: '',
          consigneePhone: '',
          startTime: '',
          endTime: '',
          mallOrderIds: '',
          poiName: '',
          successTimeStart: '',
          successTimeEnd: '',
          isHand: 1
        },
        // 表格列
        columns: [
          {
            type: 'index',
            width: 60,
            align: 'center'
          },
          {
            title: '核销码',
            minWidth: 120,
            key: 'voucherCode'
          },
          {
            title: '订单编号',
            minWidth: 190,
            key: 'mallOrderCode'
          },
          {
            title: '订单ID',
            minWidth: 190,
            key: 'mallOrderId'
          },
          {
            title: '手机号码',
            minWidth: 120,
            key: 'username'
          },
          {
            title: '核销门店',
            minWidth: 120,
            key: 'poiName'
          },
          {
            title: '清洗件数',
            minWidth: 120,
            key: 'goodsNum'
          },
          {
            title: '订单状态',
            slot: 'orderState',
            align: 'center',
            width: 120
          },
          {
            title: '核销时间',
            key: 'vouchertime',
            width: 150
          },
          {
            title: '操作',
            slot: 'action',
            minWidth: 200,
            align: 'center'
          }
        ],
        // 表格数据
        data: [],
        failOrderColumns: [
          {
            title: '订单编号',
            minWidth: 190,
            key: 'orderCode'
          },
          {
            title: '订单标题',
            minWidth: 280,
            key: 'orderTitle',
            ellipsis: true
          }
        ],
        failOrderData: [],
        // 面包屑
        breadcrumb: [
          { name: '首页', url: '', icon: 'ios-home-outline', size: 18 },
          { name: '洗衣管理', url: '', icon: '', size: 0 },
          { name: '手动录单', url: '', icon: '', size: 0 }
        ]
      };
    },
    created() {
      // 订单-列表查询
      this.findOrderMallList();
    },
    methods: {
      addHandle() {
        this.$refs.addOrderOpe.show();
      },
      batchAddHandle() {},
      // 订单-列表查询
      findOrderMallList() {
        this.isTableLoading = true;
        this.axios
          .post('/orderMall/findOrderMallList', this.params)
          .then(res => {
            console.log(res);
            this.isTableLoading = false;
            if (res.status == 200) {
              this.total = res.data.total;
              this.data = res.data.rows;
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '查询订单列表接口报错',
                duration: 0
              });
            }
          });
      },
      // 是否删除订单
      isDeleteOrderMall(row) {
        // console.log(row)
        this.$Modal.confirm({
          title: `是否删除当前订单？`,
          onOk: () => {
            // this.$Message.info('您点击了确定.');
            this.deleteOrderMall(row);
          },
          onCancel: () => {
            this.$Message.info('您点击了取消.');
          }
        });
      },

      // 删除订单
      deleteOrderMall(row) {
        this.$Spin.show();
        this.axios
          .post('/orderMall/deleteOrderMall', {
            mallOrderId: row.mallOrderId
          })
          .then(res => {
            console.log(res);
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            if (res.status == 200) {
              this.$Message.success('操作成功.');
              this.findOrderMallList();
            }
            if (res.status == 201) {
              // this.$Message.error(res.msg);
              this.$Notice.error({
                title: '删除订单失败',
                desc: res.msg
              });
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '删除订单接口报错',
                duration: 0
              });
            }
          });
      },
      // 导出订单Excel
      exportExcel() {
        this.$Spin.show();
        this.axios
          .post('/orderMall/exportExcel', this.params, {
            responseType: 'arraybuffer'
          })
          .then(res => {
            console.log(res);
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            // console.log(res);
            let blob = new Blob([res], { type: 'Files' });
            let csvUrl = URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.href = csvUrl;
            // 下载xlsx文件
            link.download = '商品订单列表.xls';
            link.click();
            if (res.status == 201) {
              // this.$Message.error(res.msg);
              this.$Notice.error({
                title: '删除订单失败',
                desc: res.msg
              });
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '删除订单接口报错',
                duration: 0
              });
            }
          });
      },
      // 显示操作模态框
      showOrderOpe(row) {
        this.$refs.orderOpe.show(row);
      },

      // 日期条件赋值
      changeDate(e) {
        this.params.successTimeStart = e[0];
        this.params.successTimeEnd = e[1];
      },
      // 重置筛选条件
      resetScreen() {
        this.params.mallOrderCode = '';
        this.params.orderState = '';
        this.params.nickName = '';
        this.params.mobile = '';
        this.params.consigneeName = '';
        this.params.consigneePhone = '';
        this.params.successTimeStart = '';
        this.params.successTimeEnd = '';
        this.params.code = '';
        this.dateInit = '';
      },
      // 改变页数
      changePage(e) {
        this.params.page = e;
        this.findOrderMallList();
      },
      // 改变页容量
      changePageSize(e) {
        this.params.rows = e;
        this.findOrderMallList();
      },
      // 在多选模式下有效，选中某一项时触发
      selectTable(selection, row) {
        this.selectData = selection;
      },
      // 在多选模式下有效，取消选中某一项时触发
      selectCancelTable(selection, row) {
        this.selectData = selection;
      },
      // 在多选模式下有效，点击全选时触发
      selectAllTable(selection) {
        this.selectData = selection;
      },
      // 在多选模式下有效，点击取消全选时触发
      selectAllCancelTable(selection) {
        this.selectData = selection;
      },
      batchOpe() {
        let arr = [];
        if (this.selectData.length) {
          this.selectData.forEach(v => {
            arr.push(v.mallOrderId);
          });
        }
        this.params.mallOrderIds = arr.join(',');
        if (this.params.mallOrderIds) {
          this.$Modal.confirm({
            title: `确定导出选中的订单？`,
            onOk: () => {
              // this.$Message.info('您点击了确定.');
              this.exportExcel();
            },
            onCancel: () => {
              this.$Message.info('您点击了取消.');
            }
          });
        } else {
          this.$Modal.confirm({
            title: `确定导出订单？`,
            onOk: () => {
              // this.$Message.info('您点击了确定.');
              this.exportExcel();
            },
            onCancel: () => {
              this.$Message.info('您点击了取消.');
            }
          });
        }
      },
      // 上传之前
      beforeUpload() {
        this.$Spin.show();
      },
      // 上传失败
      onError() {
        this.$Spin.hide();
        this.$Message.error('上传出错！');
      },
      // 导入excel成功之后返回的数据
      uploadSuccess(response, file, fileList) {
        console.log(response);
        setTimeout(() => {
          this.$Spin.hide();
        }, 300);
        if (response.status == 200) {
          this.$Message.success('操作成功');
          this.importSuccess = response.data.successNum;
          this.importFailed = response.data.failureNum;
          this.failOrderData = response.data.failOrder;
        }
        if (response.status == 201) {
          this.$Message.error(response.msg);
        }
        if (response.status == 500) {
          this.$Notice.error({
            title: '服务器内部错误',
            desc: response.msg || '服务器错误',
            duration: 0
          });
        }
      }
    },
    components: {
      hsBreadcrumb,
      orderOpe,
      addOrderOpe
    }
  };
</script>

<style scoped lang="less">
  .hs-upload-image-box {
    width: 485px;
    display: flex;
    align-items: center;
    justify-content: center;

    .hs-upload-add {
      cursor: pointer;
      width: 100%;
      height: 43px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed #cccccc;
      transition: all 0.3s;

      &:hover {
        color: #2d8cf0;
        border: 1px dashed #2d8cf0;
      }
    }
  }
  .z-import-message {
    margin: 10px 0;
  }
</style>
